package com.ruoyi.system.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.dto.JfOrMbTotalDTO;
import com.ruoyi.system.dto.ListByTypeAndTime;
import com.ruoyi.system.dto.UserShangDai;
import com.ruoyi.system.input.ListByType;
import com.ruoyi.system.input.Recharge;
import com.ruoyi.system.input.SortByType;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IUserService;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

/**
 * 用户管理Controller
 *
 * @author ruoyi
 * @date 2022-05-24
 */
@RestController
@RequestMapping("/system/my-user")
public class UserController extends BaseController
{
    @Autowired
    private IUserService userService;
    @Resource
    private UserMapper userMapper;

    @Resource
    private OrderListMapper orderListMapper;

    @Resource
    private ProfitJifenMapper profitJifenMapper;


    @Resource
    private ProfitMoneyMapper profitMoneyMapper;

//
//    @PostMapping("/changeAvatarFrame")
//
//    public AjaxResult changeAvatarFrame(@RequestBody Map<String,Object> map)
//
//    {
//        String userId = (String) map.get("userId");
//        Integer avatarFrame = (Integer) map.get("avatarFrameId");
//        logger.info("userId:{}---avatarFrame: {}",userId,avatarFrame);
//        User user = userMapper.selectUserById(userId);
//        user.setAvatarFrameId(avatarFrame);
//        int i = userMapper.updateUser(user);
//        logger.info("更新用户头像框： {}",i);
//        return AjaxResult.success("更新成功");
//    }




    @PostMapping("/changeUserToPrivateDq") //更新用户打拳账号
    public AjaxResult changeUserToPriavteDq(@RequestParam String userId)
    {
        User user = userMapper.selectUserById(userId);
        user.setUserTodayMoney(user.getMoney());
        user.setIfPrivateDq(1);

        return AjaxResult.success(userMapper.updateUser(user));
    }


//    @GetMapping("/rechargeTotal")
//    public AjaxResult rechargeTotal(@Req)



    // type : 类型，1 后台充值（积分 + m币） 2下单赠送（积分） 3 积分抽奖（积分+M币） 4积分转增（积分）

    /**
     *
     * @param jfOrMbTotalDTO
     * @return
     */
    @PostMapping("/jfOrMbTotal")
    public AjaxResult jfOrMbTotal(@RequestBody JfOrMbTotalDTO jfOrMbTotalDTO)
    {
        logger.info("jfOrMbTotalDTO : {}", JSONObject.toJSONString(jfOrMbTotalDTO));
       List<ProfitJifen> profitJifenList = profitJifenMapper.selectProfitByType(jfOrMbTotalDTO);
        BigDecimal sum = profitJifenMapper.selectProfitSum(jfOrMbTotalDTO);
       if(profitJifenList.size()!=0)
       {
           return AjaxResult.success(MapUtil.builder().put("sum",sum)
                   .put("list",profitJifenList.size()>5000?profitJifenList.subList(0,5000):profitJifenList).build());
       }


        return AjaxResult.success(MapUtil.builder().put("sum",0).put("list",new ArrayList<>()).build());
    }




    @PostMapping("/profitMoneyChangeByTypeV2")
    public AjaxResult profitMoneyChangeByTypeV2(@RequestBody ListByTypeAndTime listByType)
    {
        logger.info("profitMoneyChangeByTypeV2 : {}", JSONObject.toJSONString(listByType));
        List<ProfitMoney> profitMoneyList = profitMoneyMapper.selectProfitByTypeV2(listByType);
        BigDecimal sum = profitMoneyMapper.selectProfitSum(listByType);
        if(profitMoneyList.size()!=0)
        {
            return AjaxResult.success(MapUtil.builder().put("sum",sum)
                    .put("list",profitMoneyList.size()>5000?profitMoneyList.subList(0,5000):profitMoneyList).build());
        }
        return AjaxResult.success(MapUtil.builder().put("sum",0).put("list",new ArrayList<>()).build());


    }
    /**
     * 根据类型查看余额变动记录 类型，1 后台充值 2在线充值 3 消费 4 提现 5 提现返还 6商品回收 7 商品回收 8商城抵扣
     * @param listByType
     * @return
     */
    @PostMapping("/profitMoneyChangeByType")
    public AjaxResult profitMoneyChangeByType(@RequestBody ListByTypeAndTime listByType)
    {

        Double aDouble = profitMoneyMapper.selectRangeSum(listByType.getType(),
                listByType.getStart(), listByType.getEnd());

        List<ProfitMoney> profitMonies = profitMoneyMapper.selectRangeList(listByType.getType(),
                listByType.getStart(), listByType.getEnd());
        profitMonies.forEach(
                p->{
                    p.setUser(userMapper.selectUserById(p.getUserId()));
                }
        );
        AtomicReference<BigDecimal> privateUser =new AtomicReference<>(new BigDecimal(0));
        if(listByType.getIfPrivate()==1)
        {
            profitMonies.forEach(
                    p->{
                        if(p.getUser().getIfPrivate()==1)
                        {
                             privateUser.getAndSet(privateUser.get().add(p.getChange()));
                        }
                    }
            );

            return AjaxResult.success(MapUtil.builder(new HashMap<String,Object>())
                    .put("sum",listByType.getType()==3?
                            privateUser.get().negate() : privateUser.get()
                    ).put("list", profitMonies.stream().filter(p->p.getUser().getIfPrivate()==1).collect(Collectors.toList()))
                    .build());

        }else if(listByType.getIfPrivate()==0)
        {
            profitMonies.forEach(
                    p->{
                        if(p.getUser().getIfPrivate()==0)
                        {
                            privateUser.getAndSet(privateUser.get().add(p.getChange()));
                        }
                    }
            );

            return AjaxResult.success(MapUtil.builder(new HashMap<String,Object>())
                    .put("sum",listByType.getType()==3?
                            privateUser.get().negate() : privateUser.get()
                    ).put("list", profitMonies.stream().filter(p->p.getUser().getIfPrivate()==0).collect(Collectors.toList()))
                    .build());
        }else {
            if(aDouble==null)
            {
                aDouble= Double.valueOf(0);
            }
            return AjaxResult.success(MapUtil.builder(new HashMap<String,Object>())
                    .put("sum",listByType.getType()==3?
                            -aDouble : aDouble
                    ).put("list",profitMonies)
                    .build());

        }


    }

    @Autowired
    private WxOrderListMapper wxOrderListMapper;

    @Autowired
    private YfsOrderListMapper yfsOrderListMapper;

    @Autowired
    private UserActiveCardRecordMapper userActiveCardRecordMapper;


    @DeleteMapping("/bag")
    public AjaxResult bag(@RequestParam("id")Integer id,@RequestParam("source")Integer source){
        logger.info("id:{},source:{}",id,source);
        Integer delete = 0;
        if(source==0) {
            delete = yfsOrderListMapper.deleteByOrderId(id);
        }else if(source==1){
            delete =  wxOrderListMapper.deleteByOrderId(id);
        }else if(source==2) {
            delete = userActiveCardRecordMapper.deleteByOrderId(id);
        }else {
            return AjaxResult.error("参数错误");
        }
        return AjaxResult.success("删除成功"+delete);

    }



    @PostMapping("/userShangDai") //用户赏袋或者保险柜
    public AjaxResult userShangDai(@RequestBody UserShangDai userShangDai)
    {

        String userId = userShangDai.getUserId(); // 获取Token中UserId

        List<WxOrderList> wxOrderLists;
        List<YfsOrderList> yfsOrderLists;
        List<UserActiveCardRecordVo> list;
        int count = 0;


        wxOrderLists = wxOrderListMapper.selectListByGoodsListId(userId, userShangDai.getInsurance(), 1); //状态默认 1
        BigDecimal totalPrice = new BigDecimal(0);
        for (WxOrderList orderList : wxOrderLists) {
                count += orderList.getCount();
                totalPrice = totalPrice.add(orderList.getOutPrice().multiply(new BigDecimal(orderList.getCount())));
        }

        logger.info("wxOrderList {}", JSONObject.toJSONString(wxOrderLists));

        yfsOrderLists = yfsOrderListMapper.selectListByGoodsListId(userId, userShangDai.getInsurance(), 1); //状态默认 1
        for (YfsOrderList yfsOrderList : yfsOrderLists) {
                if(yfsOrderList.getCount()!= null)
                {
                    count += yfsOrderList.getCount();
                }else{
                    count += 1;
                    yfsOrderList.setCount(1);
                }
                totalPrice = totalPrice.add(yfsOrderList.getOutPrice().multiply(new BigDecimal(yfsOrderList.getCount())));

            }
        logger.info("yfsOrderList {}", JSONObject.toJSONString(yfsOrderLists));
        //
        list = userActiveCardRecordMapper.getPrizeRecordByUserId(userId, userShangDai.getInsurance());


        for(UserActiveCardRecordVo userActiveCardRecordVo : list)
        {
            totalPrice = totalPrice.add(userActiveCardRecordVo.getOutPrice().multiply(new BigDecimal(userActiveCardRecordVo.getCount())));
        }


        int total = list.stream().mapToInt(UserActiveCardRecordVo::getCount).sum();

        count += total;


        List<Object> allList = new ArrayList<>();
        yfsOrderLists.forEach(
                yfsOrderList -> {
                    yfsOrderList.setSource(0);
                });
        wxOrderLists.forEach(
                wxOrderList -> {
                    wxOrderList.setSource(1);
                });
        list.forEach(
                userActiveCardRecordVo -> {
                    userActiveCardRecordVo.setSource(2);
                });
        allList.addAll(yfsOrderLists);
        allList.addAll(wxOrderLists);
        allList.addAll(list);
        logger.info("allList {}", JSONObject.toJSONString(allList));
        Map<Object, Object> allBuild = MapUtil.builder(new HashMap<>()).put("count",count)
                .put("list",allList)
                .put("totalPrice",totalPrice)
                .build();
        return AjaxResult.success(allBuild);
    }


    @PostMapping("/editMb") //编辑用户
    public AjaxResult editMb(@RequestParam("userId")String userId,@RequestParam("change")Integer newMb)
    {

        logger.info("userId:{}---change: {}",userId,newMb);
        User user = userMapper.selectUserById(userId);
        user.setMb(user.getMb()+newMb);
        int i = userMapper.updateUser(user);
        logger.info("更新用户Mb： {}",i);
        //然后mb 账变记录  allsetv
        ProfitJifen profitJifen =new ProfitJifen();
        profitJifen.setUserId(userId);
        profitJifen.setMoney(BigDecimal.valueOf(user.getMb()));
        profitJifen.setChange(new BigDecimal(newMb));
        profitJifen.setType(1);
        profitJifen.setAdminId(0L);
        profitJifen.setCreator(0L);
        profitJifen.setIfMb(1);

        int i1 = profitJifenMapper.insertProfitJifen(profitJifen);
        logger.info("更新用户Mb记录： {}",i1);


        return AjaxResult.success("更新成功");
    }


    @PostMapping("/fenghao")
    public AjaxResult fenghao(@RequestParam("openId")String openId,@RequestParam("time")Integer time)
    {
        if(time==666)
        {
            StpUtil.untieDisable(openId);
            userMapper.updateUserStatus(openId,1);
            return AjaxResult.success("解封成功");
        }
        logger.info("openId:"+openId);
        StpUtil.kickout(openId);
// 再封禁账号
        StpUtil.disable(openId, time);
        logger.info("该账号是否封号： "+StpUtil.isDisable(openId)+"");
        userMapper.updateUserStatus(openId,-1);


        return AjaxResult.success();
    }

    /**
     * 查询用户管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:my-user:list')")
    @GetMapping("/list")
    public TableDataInfo list(User user)
    {
        startPage();
        List<User> list = userService.selectUserList(user);
        for (User user1 : list) {
            boolean disable = StpUtil.isDisable(user1.getOpenid());
            if(disable)
            {
                user1.setStatus(-1);//-1 封号
                user1.setRemainingTime(StpUtil.getDisableTime(user1.getOpenid()));
            }else {
                user1.setRemainingTime(0L);
            }

        }

        return getDataTable(list);
    }


    @PostMapping("/status")
    public AjaxResult status(@RequestParam("openIds")String[] openId)
    {

        return AjaxResult.success();
    }

    /**
     *
     * 用户统计
     *  总用户数 今日新增人数 待处理发货订单 当前玩家总余额
     */
    @GetMapping("/total")
    public AjaxResult total()
    {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String start = sdf.format(new Date(getTodayStartTime()));
        String now =sdf.format(new Date());
        logger.info("start:{} now: {}",start,now);
        int totalCount = userMapper.selectUserCount();
        int todayCount = userMapper.selectTodayCount(start,now);
        int delivery = orderListMapper.selectOrderListByDeliveryStatus(2);
        Double totalMoney = userMapper.selectUserCountMoney();
        Map hashMap =new HashMap();
        hashMap.put("totalCount",totalCount);
        hashMap.put("todayCount",todayCount);
        hashMap.put("delivery",delivery);
        hashMap.put("totalMoney",totalMoney);

        return AjaxResult.success(hashMap);


    }

    public static long getTodayStartTime() {
        //设置时区
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTimeInMillis();
    }



    /**
     * 余额/积分 充值
     */
    @PostMapping("/recharge")
    @PreAuthorize("@ss.hasPermi('system:my-user:recharge')")
    @Transactional //事务
    public  AjaxResult recharge(@RequestBody Recharge recharge)
    {
        if(recharge.getType()==0)
        {
            //余额充值
            String userId = recharge.getUserId();
            BigDecimal money= userService.selectUserById(userId).getMoney();
            if(new BigDecimal(recharge.getChange()).add(money).compareTo(new BigDecimal(0))<0)
            {
                return AjaxResult.error("余额最低为0！！");
            }
            //更新余额
            int change =  userService.updateUserMoneyOrJf(userId,recharge.getChange(),recharge.getType());
            logger.info("余额更新情况：{}",change);
            //更新记录
            int change2 = userService.updateRecords(userId,money,recharge.getChange(),recharge.getType(),"后台操作");
            logger.info("记录更新情况：{}",change2);
            return AjaxResult.success("余额更新成功");
        }else if(recharge.getType()==1){
            //积分充值

            String userId = recharge.getUserId();
            BigDecimal jifen= userService.selectUserById(userId).getJifen();
            if(new BigDecimal(recharge.getChange()).add(jifen).compareTo(new BigDecimal(0))<0)
            {
                return AjaxResult.error("积分最低为0！！");
            }

            int change =  userService.updateUserMoneyOrJf(userId,recharge.getChange(),recharge.getType());
            logger.info("积分更新情况：{}",change);

            //更新记录
            int change2 = userService.updateRecords(userId,jifen,recharge.getChange(),recharge.getType(),"1");
            logger.info("记录更新情况：{}",change2);
            return AjaxResult.success("积分更新成功");

        }else {
            return AjaxResult.error("傻逼 类型传错了");
        }

    }





    /**
     *  1. 余额 积分区间 查找
     *  2 . 按照 余额积分区间排序
     *
     */
    @PreAuthorize("@ss.hasPermi('system:my-user:listByType')")
    @GetMapping("/listByType")
    public TableDataInfo listByType(@RequestBody ListByType listByType)
    {

        startPage();
        logger.info(listByType.getStartNum()+"--"+listByType.getEndNum());
        List<User> list = userService.selectUserTypeList(listByType);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('system:my-user:sortByType')")
    @GetMapping("/sortByType")
    public TableDataInfo sortByType(@RequestBody SortByType sortByType)
    {

        startPage();
        logger.info(sortByType.getSortType()+"--"+sortByType.getAscOrDesc());
        List<User> list = userService.selectUserSortList(sortByType);
        return getDataTable(list);
    }






    /**
     * 导出用户管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:my-user:export')")
    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, User user)
    {
        List<User> list = userService.selectUserList(user);
        ExcelUtil<User> util = new ExcelUtil<User>(User.class);
        util.exportExcel(response, list, "用户管理数据");
    }

    /**
     * 获取用户管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:my-user:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return AjaxResult.success(userService.selectUserById(id));
    }

    /**
     * 新增用户管理
     */
    @PreAuthorize("@ss.hasPermi('system:my-user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody User user)
    {
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户管理
     */
    @PreAuthorize("@ss.hasPermi('system:my-user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody User user)
    {
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户管理
     */
    @PreAuthorize("@ss.hasPermi('system:my-user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(userService.deleteUserByIds(ids));
    }
}
